package com.furongji.education.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.furongji.education.domain.po.Subject;
import com.furongji.education.domain.vo.SubjectVo;
import com.furongji.education.mapper.SubjectMapper;
import com.furongji.education.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author furongji
 * @since 2025-05-18
 */
@Service
@RequiredArgsConstructor
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Override
    public List<SubjectVo> selectSubject() {
        List<SubjectVo> subjectVoList = new ArrayList<>();

        LambdaQueryWrapper<Subject> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Subject::getParentId, "0");
        List<Subject> subjectList = super.list(wrapper);

        for (Subject subject : subjectList) {
            LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Subject::getParentId, subject.getId());
            List<Subject> children = super.list(queryWrapper);
            SubjectVo subjectVo = new SubjectVo(subject.getId(), subject.getTitle(), children);
            subjectVoList.add(subjectVo);
        }
        return subjectVoList;
    }

    @Override
    public void addSubject(String name, String parentId) {
        Subject subject = new Subject();
        subject.setTitle(name);
        subject.setParentId(parentId);
        super.save(subject);
    }

    @Override
    public void deleteBySubjectId(String id) {
        Subject subject = super.getById(id);
        if (subject.getParentId().equals("0")) {
            // 顶级分类
            LambdaQueryWrapper<Subject> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Subject::getParentId, id);
            super.remove(wrapper);
        }
        super.removeById(id);
    }
}
